package main

import (
	"context"
	"log"
	"net/http"
	"xiaoniu-task/internal/api"
	"xiaoniu-task/internal/beat"
	"xiaoniu-task/internal/biz"
	"xiaoniu-task/internal/config"
	"xiaoniu-task/internal/job"
	"xiaoniu-task/internal/newbond"
	"xiaoniu-task/internal/yinghuadongman"
	"xiaoniu-task/pkg"
)

// 客户端启动类
func main() {
	// 加载配置
	initConfig := config.InitClientConfig()
	if !initConfig {
		log.Fatalln("App config file read error!")
		return
	}
	// 开启后台定时任务
	go biz.StartConsumer()

	// 心跳任务
	go beat.StartHeartBeatJob()

	// 注册任务
	job.RegisterTask("NewBondJob", NewBondJob)
	job.RegisterTask("ComicJob", ComicJob)

	mux := http.NewServeMux()
	mux.HandleFunc("/run", api.RunHandler)
	mux.HandleFunc("/getLog", api.GetLogHandler)
	mux.HandleFunc("/queryLocalLog", api.QueryLocalLogHandler)
	mux.HandleFunc("/gracefulShutdown", api.GracefulShutdownHandler)
	server := &http.Server{
		Addr:    ":" + config.ClientRation.Port,
		Handler: mux,
	}
	go func() {
		// 启动整个程序
		server.ListenAndServe()
	}()

	log.Println("client is already running....")

	// 如果没有收到所有任务都完成的信号，会一直阻塞在这里
	<-biz.CompleteChan
	// 优雅停机
	server.Shutdown(context.Background())
}

func NewBondJob(taskLog *log.Logger, request *pkg.ClientTaskRequest) string {
	newbond.DoJob(taskLog)
	return "执行完成"
}

func ComicJob(taskLog *log.Logger, request *pkg.ClientTaskRequest) string {
	yinghuadongman.DoJob(taskLog)
	return "执行完成"
}
